<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Signature with Chinese OCR</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
        #controls {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <canvas id="signatureCanvas" width="1000" height="600"></canvas>
    <div id="controls">
        <button onclick="clearCanvas()">Clear</button>
        <button onclick="extractText()">Extract Text</button>
    </div>
    <script>
        const canvas = document.getElementById('signatureCanvas');
        const ctx = canvas.getContext('2d');
        let drawing = false;

        canvas.addEventListener('mousedown', (e) => {
            drawing = true;
            ctx.beginPath();
            ctx.moveTo(e.offsetX, e.offsetY);
        });

        canvas.addEventListener('mousemove', (e) => {
            if (drawing) {
                ctx.lineTo(e.offsetX, e.offsetY);
                ctx.stroke();
            }
        });

        canvas.addEventListener('mouseup', () => {
            drawing = false;
        });

        canvas.addEventListener('mouseleave', () => {
            drawing = false;
        });

        function clearCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        async function extractText() {
            // 将Canvas内容转换为图像数据
            const imageData = canvas.toDataURL('image/png');
            const img = new Image();
            img.src = imageData;

            img.onload = async () => {
                // 创建离屏Canvas用于预处理图像
                const offCanvas = document.createElement('canvas');
                const offCtx = offCanvas.getContext('2d');
                offCanvas.width = img.width;
                offCanvas.height = img.height;

                // 绘制图像到离屏Canvas
                offCtx.drawImage(img, 0, 0);

                // 获取图像数据
                const imageData = offCtx.getImageData(0, 0, offCanvas.width, offCanvas.height);
                const data = imageData.data;

                // 图像预处理（简单的二值化处理）
                for (let i = 0; i < data.length; i += 4) {
                    const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                    const threshold = 200; // 根据需要调整阈值
                    const value = brightness >= threshold ? 255 : 0;
                    data[i] = data[i + 1] = data[i + 2] = value;
                }

                // 将预处理后的图像数据放回离屏Canvas
                offCtx.putImageData(imageData, 0, 0);

                // 将离屏Canvas的内容转换为图像数据URL
                const processedImageData = offCanvas.toDataURL('image/png');

                try {
                    const result = await Tesseract.recognize(
                        processedImageData,
                        'chi_sim', // 使用简体中文语言包
                        {
                            logger: m => console.log(m)
                        }
                    );
                    console.log('Extracted Text:', result.data.text);
                    alert('Extracted Text: ' + result.data.text);
                } catch (error) {
                    console.error('Error:', error);
                }
            };
        }
    </script>
    <!-- Load Tesseract.js library -->
    <script src="https://cdn.jsdelivr.net/npm/tesseract.js@2.1.4/dist/tesseract.min.js"></script>
</body>
</html>
